package fact.view.model;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.CustomScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import com.icesoft.faces.component.tree.IceUserObject;

import fact.view.DAO.TreeNodeDAO;
import fact.view.DTO.NavDTO;
import fact.view.DTO.NodeDTO;
import fact.view.DTO.NodeObjectDTO;
import fact.view.DTO.SegmentDTO;
import fact.view.controller.LoginBean;
import fact.view.model.FactReportModelBean;



@ManagedBean(name= "leftNavBean")
//@RequestScoped
@CustomScoped(value = "#{window}")
public class LeftNavModelBean   implements Serializable {
    
    public static final String BEAN_NAME = "tree";
    public static final String IMAGE_PATH = "/xmlhttp/css/rime/css-images/";
    public static String imgUrl="/FACTENTRY/javax.faces.resource/navIcon/";
    public static String imgUrl1="/FACTENTRY/javax.faces.resource/";
    
    
    //public static final String IMAGE_ICON = "tree_document.gif";
    //public static final String IMAGE_ICON ="/FACTENTRY/javax.faces.resource/pink.png.jsf?ln=images";
    //public static final String IMAGE_CLOSED = "tree_folder_closed.gif";
    //public static final String IMAGE_OPEN = "tree_folder_open.gif";
    
    public static final String RED_IMAGE_OPEN = imgUrl+"redOpen.png"+".jsf?ln=images";
    public static final String RED_IMAGE_CLOSE = imgUrl+"redClose.png"+".jsf?ln=images";
    public static final String GREEN_IMAGE_OPEN = imgUrl+"greenOpen.png"+".jsf?ln=images";
    public static final String GREEN_IMAGE_CLOSE = imgUrl+"greenClose.png"+".jsf?ln=images";
    public static final String YELLOW_IMAGE_OPEN = imgUrl+"yellowOpen.png"+".jsf?ln=images";
    public static final String YELLOW_IMAGE_CLOSE = imgUrl+"yellowClose.png"+".jsf?ln=images";
    
    public static final String RED_IMAGE_LEAF = imgUrl+"leafRed.png"+".jsf?ln=images";
    public static final String GREEN_IMAGE_LEAF = imgUrl+"leafGreen.png"+".jsf?ln=images";
    public static final String YELLOW_IMAGE_LEAF = imgUrl+"leafYellow.png"+".jsf?ln=images";
   
    public static final String REPORT_ICON = imgUrl+"report1.png"+".jsf?ln=images";
    
    private DefaultTreeModel model;
    
    @ManagedProperty(value="#{nodeModelBean}")
    private TreeNodeDAO nodeModelBean;
    
    @ManagedProperty(value="#{loginBean}")
    private LoginBean loginBean;
    
    @PostConstruct
    public void init() 
    {

    	if(loginBean.getUserBean().getUserType().equalsIgnoreCase("ADMIN"))
    		model = generateAdminTree();
    	else
    		model = generateNonAdminTree();
    }


    public void refreshTree(ActionEvent event) {
    	
    	if(loginBean.getUserBean().getUserType().equalsIgnoreCase("ADMIN"))
    		model = generateAdminTree();
    	else
    		model = generateNonAdminTree();
    }

    public  DefaultTreeModel generateNonAdminTree() 
    {
    	ArrayList<NavDTO> 	  nodeList=new ArrayList<NavDTO>();
    	ArrayList<SegmentDTO> segmentList=new ArrayList<SegmentDTO>();
    	
    	try
    	{
    		nodeList=nodeModelBean.getLeftNavNodeList(loginBean.getLoginName());
    		segmentList=nodeModelBean.getSegmentList();
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}

    	// Put elements to the map
    		
        // Setup the root node
        DefaultMutableTreeNode rootNode = addNode(null, "System",
        										  0,"",
        										  0,"",
        										  0,"",
        										  "", false);
        
        DefaultTreeModel toReturn = new DefaultTreeModel(rootNode);
        DefaultMutableTreeNode folderNode = null;
        
        int preMakeId=0;
        int currentMakeId;
        DefaultMutableTreeNode preNode=null;
        for(int i=0;i<nodeList.size();i++)
        {
        	currentMakeId=nodeList.get(i).getMakeId();
        	
        	if(preMakeId!=currentMakeId)
        	{
        		folderNode=addNode(rootNode, ((NavDTO)nodeList.get(i)).getMakeName(), 
        				nodeList.get(i).getMakeId(),nodeList.get(i).getMakeName(),
        				nodeList.get(i).getMakeId(),nodeList.get(i).getMakeName(),
        				nodeList.get(i).getMarketId(),nodeList.get(i).getMarketName(),
        				"",false);
        		
        		preNode=folderNode;
        		
        		folderNode=addNode(folderNode, ((NavDTO)nodeList.get(i)).getMarketName(), 
        				nodeList.get(i).getMarketId(),nodeList.get(i).getMakeName(),
        				nodeList.get(i).getMakeId(),nodeList.get(i).getMakeName(),
        				nodeList.get(i).getMarketId(),nodeList.get(i).getMarketName(),
        				"",false);
        		
        		for(int j=0;j<segmentList.size();j++)
        		{
        			
        			addNode(folderNode, segmentList.get(j).getSegmentName(),
        					segmentList.get(j).getSegmentId(),segmentList.get(j).getSegmentName(),
        					nodeList.get(i).getMakeId(),nodeList.get(i).getMakeName(),
        					nodeList.get(i).getMarketId(),nodeList.get(i).getMarketName(),
        					"N", true);
        		}
        	}        	
        	else
        	{
        		
        		folderNode=addNode(preNode, ((NavDTO)nodeList.get(i)).getMarketName(), 
        				nodeList.get(i).getMarketId(),nodeList.get(i).getMarketName(),
        				nodeList.get(i).getMakeId(),nodeList.get(i).getMakeName(),
        				nodeList.get(i).getMarketId(),nodeList.get(i).getMarketName(),
        				"",false);
        		
        		for(int j=0;j<segmentList.size();j++)
        		{
        			
        			addNode(folderNode, segmentList.get(j).getSegmentName(),
        					segmentList.get(j).getSegmentId(),segmentList.get(j).getSegmentName(),
        					nodeList.get(i).getMakeId(),nodeList.get(i).getMakeName(),
        					nodeList.get(i).getMarketId(),nodeList.get(i).getMarketName(),
        					"N", true);
        		}
        	}
        	preMakeId=currentMakeId;
        }
        
        folderNode=addNode(rootNode, "Reports",-99,"Make Name",0,"Market Name",0,"","",true);
        
        return toReturn;
    }
    
    public static DefaultMutableTreeNode addNode(DefaultMutableTreeNode parent, String text,
    		int nodeId,String nodeName,
    		int makeId,String makeName,
    		int marketId,String marketName,
    		String status,boolean isLeaf) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode();
        NodeObjectDTO userObject = new NodeObjectDTO(node);
        node.setUserObject(userObject);

        // Customize our new node
        userObject.setLeaf(isLeaf);
        userObject.setText(text);
        userObject.setTooltip(text);
        node.setAllowsChildren(!isLeaf);
        
        userObject.setAction(String.valueOf(nodeId));
        userObject.setSegmentId(nodeId);
        userObject.setSegmentName(nodeName);
        userObject.setMakeId(makeId);
        userObject.setMakeName(makeName);
        userObject.setMarketId(marketId);
        userObject.setMarketName(marketName);
        
        
        userObject.setBranchContractedIcon(RED_IMAGE_CLOSE);
        userObject.setBranchExpandedIcon(RED_IMAGE_OPEN); 
        
        
        if(text.equalsIgnoreCase("Reports"))
        {
        	userObject.setLeafIcon(REPORT_ICON);
        }
        else
        {
       
	        if(isLeaf==true)
	        {
	        	if(status==null || status.equalsIgnoreCase("N"))
	            	userObject.setLeafIcon(RED_IMAGE_LEAF);
	        	else if(status.equalsIgnoreCase("S"))
	        		userObject.setLeafIcon(YELLOW_IMAGE_LEAF);
	        	else if(status.equalsIgnoreCase("A"))
	            	userObject.setLeafIcon(GREEN_IMAGE_LEAF);
	            	
	        }
	        else
	        {
	            userObject.setBranchContractedIcon(RED_IMAGE_CLOSE);
	            userObject.setBranchExpandedIcon(RED_IMAGE_OPEN);        
	
	        }
        }

    // Expand if we're not a leaf
    if (!isLeaf) {
        userObject.setExpanded(true);
    }

    // Add the completed node to the parent
    if (parent != null) {
        parent.add(node);
    }

    return node;
    }
    
    public  DefaultTreeModel generateAdminTree() 
    {

        // Setup the root node
        DefaultMutableTreeNode rootNode = addNode(null, "Admin",
        										  0,"",
        										  0,"",
        										  0,"",
        										  "", false);
        
        DefaultTreeModel toReturn = new DefaultTreeModel(rootNode);

        // Setup each folder and child
        DefaultMutableTreeNode folderNode = null;
        
        folderNode = addAdminNode(rootNode, "Master Form Management","","user.png", false);
        addAdminNode(folderNode, "User","admin/user.jsf","leaf.png",true);
        addAdminNode(folderNode, "Market","admin/market.jsf","leaf.png",true);
        addAdminNode(folderNode, "Make","admin/make.jsf","leaf.png",true);
        addAdminNode(folderNode, "Role","admin/role.jsf","leaf.png",true);
        addAdminNode(folderNode, "Responsibility","admin/responsibility.jsf","leaf.png",true);
        
        folderNode = addAdminNode(rootNode, "Fact Managment","","fact.png", false);
        //addAdminNode(folderNode, "Node Types","","leaf.png",true);
        addAdminNode(folderNode, "Segment","admin/segment.jsf","leaf.png",true);
        addAdminNode(folderNode, "Scenario","admin/scenario.jsf","leaf.png",true);
        addAdminNode(folderNode, "Node Hierarchy","admin/nodeHierarchy.jsf","leaf.png",true);
        addAdminNode(folderNode, "Node Attributes","admin/nodeAttribute.jsf","leaf.png",true);        
        addAdminNode(folderNode, "Entry Sets","admin/entrySets.jsf","leaf.png",true);
        
        return toReturn;
    }

    
    public static DefaultMutableTreeNode addAdminNode(DefaultMutableTreeNode parent, String text,String actionName,String img,boolean isLeaf) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode();
        NodeObjectDTO userObject = new NodeObjectDTO(node);
        node.setUserObject(userObject);

        // Customize our new node
        userObject.setLeaf(isLeaf);
        userObject.setText(text);
        userObject.setTooltip(text);
        userObject.setAction(actionName);
        
        node.setAllowsChildren(!isLeaf);
        
        
        if(isLeaf==true)
        {
            	userObject.setLeafIcon(imgUrl1+img+".jsf?ln=images");
            	
        }
        else
        {
        	
            userObject.setBranchContractedIcon(imgUrl1+img+".jsf?ln=images");
            userObject.setBranchExpandedIcon(imgUrl1+img+".jsf?ln=images");        

        }

    // Expand if we're not a leaf
    if (!isLeaf) {
        userObject.setExpanded(true);
    }

    // Add the completed node to the parent
    if (parent != null) {
        parent.add(node);
    }

    return node;
    }

    public static String makeIcon(String image) {
        return IMAGE_PATH + image;
    }

    public DefaultTreeModel getModel() { return model; }
    public void setModel(DefaultTreeModel model) { this.model = model; }


	public TreeNodeDAO getNodeModelBean() {
		return nodeModelBean;
	}


	public void setNodeModelBean(TreeNodeDAO nodeModelBean) {
		this.nodeModelBean = nodeModelBean;
	}


	public LoginBean getLoginBean() {
		return loginBean;
	}


	public void setLoginBean(LoginBean loginBean) {
		this.loginBean = loginBean;
	}

    
    
    
}

